<template>
  <div>
    <el-dialog title="更新" :model-value="updateDialogVisible" @open="handleOpen" :before-close="handleCancel" width="30%">
      <el-form :model="formData" :rules="rules" label-width="100px" ref="updateForm">
        <el-form-item label="系统编号:" prop="id">
          <el-input v-model="formData.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="父级:" prop="parentId">
          <el-tree-select v-model="formData.parentId" :data="formCfg.authorityTree" :render-after-expand="false"
                          :default-expand-all="true" :check-strictly="true" show-checkbox style="width: 240px" />
        </el-form-item>
        <el-form-item label="类型:" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型">
            <el-option v-for="one in authorityTypeList" :key="one.id" :label="one.typeName" :value="one.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称:" prop="authorityName">
          <el-input v-model="formData.authorityName" placeholder="请输入权限名称"></el-input>
        </el-form-item>
        <el-form-item label="排序:" prop="orderNo">
          <el-input-number v-model="formData.orderNo" :min="1" :step="1" :precision="0" />
        </el-form-item>
        <el-form-item v-show="formData.type !== 1" label="路由路径:" prop="path">
          <el-input v-model="formData.path" placeholder="首尾不以/结尾的路由路径"></el-input>
        </el-form-item>
        <el-form-item label="后端请求:" prop="relateBackUriList">
          <el-select v-model="formData.relateBackUriList" :multiple="true" :filterable="true" placeholder="选择后端请求">
            <el-option v-for="one in formCfg.backUris" :key="one" :label="one" :value="one"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="formData.type !== 1" label="组件位置:" prop="componentPath">
          <el-input v-model="formData.componentPath" placeholder="如 dept/DeptManage">
            <template #prepend>src/views/</template>
            <template #append>.vue</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="formData.type !== 1" label="菜单:" prop="showInMenu">
          <el-radio v-model="formData.showInMenu" :value="1">是</el-radio>
          <el-radio v-model="formData.showInMenu" :value="0">否</el-radio>
        </el-form-item>
        <el-form-item v-show="formData.type !== 1 && formData.showInMenu" label="图标名称:" prop="icon">
          <el-input v-model="formData.icon" placeholder="请输入图标名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel()">取消</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue';
import { authorityTypeList } from '@/config/constants';
import { queryTreeApi, listBackUriApi, modifyByIdApi, queryByIdApi } from '@/api/authorityApi';
import type { AnyObjsDefine } from '@/types/common';
import { ElMessage } from 'element-plus';

// 更新权限对应的字段
const formData = reactive({
  id: '',
  type: 0,
  authorityName: '',
  parentId: '-1',
  orderNo: 1,
  path: '',
  relateBackUriList: [],
  componentPath: '',
  showInMenu: 1,
  icon: '',
});

const formCfg = reactive({
  authorityTree: [] as AnyObjsDefine,
  backUris: [] as string[],
});

const rules = reactive({
  parentId: [{ required: true, message: '请选择父级', trigger: 'blur' }],
  authorityName: [{ required: true, message: '请填写权限名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择权限类型', trigger: 'blur' }],
  orderNo: [{ required: true, message: '请填写排序', trigger: 'blur' }],
});

const updateForm = ref();
const props = defineProps<{ updateDialogVisible: boolean; idToUpdate: string }>();
const emitter = defineEmits(["closeDialog", "updateSuccess"]);

// 打开对话框事件
function handleOpen() {
  queryByIdApi(props.idToUpdate).then(result => {
    Object.assign(formData, result.data);
  }).catch(error => {
    ElMessage.error("获取数据失败: " + error.message);
  });

  queryTreeApi().then(result => {
    formCfg.authorityTree = result.data;
    formCfg.authorityTree.unshift({ value: '-1', label: "无" });
  }).catch(error => {
    ElMessage.error("获取权限树失败: " + error.message);
  });

  listBackUriApi().then(result => {
    formCfg.backUris = result.data;
  }).catch(error => {
    ElMessage.error("获取后端 URI 失败: " + error.message);
  });
}

function handleCancel() {
  updateForm.value.resetFields();
  emitter("closeDialog");
}

// 更新权限
function onSubmit() {
  updateForm.value.validate((valid: boolean) => {
    if (!valid) return;
    const csrfToken = getCsrfToken(); // 获取最新的 CSRF Token
    modifyByIdApi(formData).then(result => {
      ElMessage({ type: "success", message: result.data });
      updateForm.value.resetFields();
      emitter("updateSuccess");
    }).catch(error => {
      ElMessage.error("更新权限失败: " + error.message);
    });
  });
}

function getCsrfToken() {
  const name = 'XSRF-TOKEN=';
  const decodedCookie = decodeURIComponent(document.cookie);
  const cookies = decodedCookie.split(';');
  for (let i = 0; i < cookies.length; i++) {
    const cookie = cookies[i].trim();
    if (cookie.indexOf(name) === 0) {
      return cookie.substring(name.length, cookie.length);
    }
  }
  console.warn('CSRF Token not found in cookies');
  return '';
}
</script>

<style scoped></style>
